import { createRouter, createWebHistory } from 'vue-router'
import { login } from '@/api'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/home/main.vue'),
      beforeEnter: async (from, to, next) => {
        const useStore = useUserStore()
        if (from.query.accessCode) {
          const params = {
            accessCode: from.query.accessCode,
          }
          const res = await login(params)
          if (res.code === '200') {
            useStore.setUserInfo(res.data)
          }
          next({ path: to.path, query: {} })
        } else {
          next()
        }
      },
    },
  ],
})

export default router
